package com.ms.content.controller;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.ms.common.utils.PageUtils;
import com.ms.common.utils.R;
import com.ms.content.entity.BargainActivityEntity;
import com.ms.content.entity.BargainingRecordEntity;
import com.ms.content.entity.GoodsEntity;
import com.ms.content.service.BargainActivityService;
import com.ms.content.service.BargainingRecordService;
import com.ms.content.service.GoodsService;
import com.ms.content.util.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ms.content.entity.BargainingItemEntity;
import com.ms.content.service.BargainingItemService;


/**
 * @author wc
 * @email sunlightcs@gmail.com
 * @date 2022-03-14 16:23:45
 */
@RestController
@RequestMapping("content/bargainingitem")
public class BargainingItemController {
    @Autowired
    private BargainingItemService bargainingItemService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private BargainActivityService bargainActivityService;

    @Autowired
    private GoodsService goodsService;


    @RequestMapping("/pay")
    public R pay(@RequestParam("uid") Long uid, @RequestParam("goodsId") Integer goodsId, @RequestParam("bkhdId") Long bkhdId) throws Exception {
        Long id = bargainingItemService.selectById(uid, goodsId, bkhdId);
        System.out.println(id);
        String s = stringRedisTemplate.opsForValue().get(goodsId + "," + uid);
        List<GoodsEntity> goodsEntities = JSONObject.parseObject(s, new TypeReference<List<GoodsEntity>>() {
        });
        GoodsEntity goodsEntity = goodsEntities.get(goodsEntities.size() - 1);
//获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(id.toString().getBytes(), "UTF-8");
        System.out.println("商户网站订单系统中唯一订单号: "+id);
        System.out.println(goodsEntity.getId());
        //付款金额，必填
        String total_amount = new String(goodsEntity.getGoodsPrice().toString().getBytes(), "UTF-8");
        //订单名称，必填
        String subject = new String(goodsEntity.getGoodsName().getBytes(), "UTF-8");
        //商品描述，可空
        String body = new String(goodsEntity.getGoodsTitle().getBytes(), "UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        System.out.println("商品订单号:" + out_trade_no);

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        System.out.println(alipayRequest);
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //输出
        return R.ok().put("connect", result);
    }

    @RequestMapping("/payy")
    public R payy(@RequestParam("bid") Long bid) throws Exception {


        //通过活动id 查询到商品id 因为是原价购买  所以直接按原价支付
        BargainActivityEntity byId = bargainActivityService.getByIda(bid);
        GoodsEntity goodsEntity = goodsService.seleByIdsj(byId.getGoodsId());


//获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(bid.toString().getBytes(), "UTF-8");
        System.out.println("商户网站订单系统中唯一订单号: "+bid);
        System.out.println(goodsEntity.getId());
        //付款金额，必填
        String total_amount = new String(goodsEntity.getGoodsPrice().toString().getBytes(), "UTF-8");
        //订单名称，必填
        String subject = new String(goodsEntity.getGoodsName().getBytes(), "UTF-8");
        //商品描述，可空
        String body = new String(goodsEntity.getGoodsTitle().getBytes(), "UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        System.out.println("商品订单号:" + out_trade_no);

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        System.out.println(alipayRequest);
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //输出
        return R.ok().put("connect", result);
    }


    /**
     * getGoodsByKey  从redis中取出最新信息
     */
    @RequestMapping("/getGoodsByKey")
    public R getGoodsByKey(@RequestParam("key") String key) {
        String s = stringRedisTemplate.opsForValue().get(key);
        List<GoodsEntity> goodsEntities = JSONObject.parseObject(s, new TypeReference<List<GoodsEntity>>() {
        });
        GoodsEntity goodsEntity = goodsEntities.get(goodsEntities.size() - 1);
        return R.ok().put("goodsEntity", goodsEntity);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = bargainingItemService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id) {
        BargainingItemEntity bargainingItem = bargainingItemService.getById(id);

        return R.ok().put("bargainingItem", bargainingItem);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody BargainingItemEntity bargainingItem) {
        bargainingItemService.save(bargainingItem);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody BargainingItemEntity bargainingItem) {
        bargainingItemService.updateById(bargainingItem);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids) {
        bargainingItemService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
